<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(C卷,200分)- 考古学家（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>有一个考古学家发现一个石碑&#xff0c;但是很可惜&#xff0c;发现时其已经断成多段&#xff0c;原地发现n个断口整齐的石碑碎片。</p> 
<p>为了破解石碑内容&#xff0c;考古学家希望有程序能帮忙计算复原后的石碑文字组合数&#xff0c;你能帮忙吗&#xff1f;</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>第一行输入 n</p> 
<ul><li>n表示石碑碎片的个数</li></ul> 
<p>第二行依次输入石碑碎片上的文字内容s&#xff0c;共有n组。 </p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>输出石碑文字的组合&#xff08;按照升序排列&#xff09;&#xff0c;行末无多余空格。</p> 
<p></p> 
<h4>备注</h4> 
<p>如果存在石碑碎片内容完全相同&#xff0c;则由于碎片间的顺序变换不影响复原后的碑文内容&#xff0c;即相同碎片间的位置变换不影响组合。</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:63px;">输入</td><td style="width:435px;">3<br /> a b c</td></tr><tr><td style="width:63px;">输出</td><td style="width:435px;">abc<br /> acb<br /> bac<br /> bca<br /> cab<br /> cba</td></tr><tr><td style="width:63px;">说明</td><td style="width:435px;">当石碑碎片上的内容为“a”&#xff0c;“b”&#xff0c;“c”时&#xff0c;则组合有“abc”&#xff0c;“acb”&#xff0c;“bac”&#xff0c;“bca”&#xff0c;“cab”&#xff0c;“cba”</td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:63px;">输入</td><td style="width:435px;">3<br /> a b a</td></tr><tr><td style="width:63px;">输出</td><td style="width:435px;">aab<br /> aba<br /> baa</td></tr><tr><td style="width:63px;">说明</td><td style="width:435px;">当石碑碎片上的内容为“a”&#xff0c;“b”&#xff0c;“a”时&#xff0c;则可能的组合有“aab”&#xff0c;“aba”&#xff0c;“baa”</td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:63px;">输入</td><td style="width:435px;">3<br /> a b ab</td></tr><tr><td style="width:63px;">输出</td><td style="width:435px;">aabb<br /> abab<br /> abba<br /> baab<br /> baba</td></tr><tr><td style="width:63px;">说明</td><td style="width:435px;">当石碑碎片上的内容为“a”&#xff0c;“b”&#xff0c;“ab”时&#xff0c;则可能的组合有“aabb”&#xff0c;“abab”&#xff0c;“abba”&#xff0c;“baab”&#xff0c;“baba”</td></tr></tbody></table> 
<p> </p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>本题是全排列求解问题。</p> 
<p></p> 
<p>关于全排列的求解可以看下&#xff1a;</p> 
<p><a href="https://fcqian.blog.csdn.net/article/details/127286788" rel="nofollow" title="LeetCode - 46 全排列_全排列 46 力扣-CSDN博客">LeetCode - 46 全排列_全排列 46 力扣-CSDN博客</a></p> 
<p></p> 
<p>关于不重复的全排列求解可以看下&#xff1a;</p> 
<p><a href="https://fcqian.blog.csdn.net/article/details/127292846" rel="nofollow" title="LeetCode - 47 全排列 II_leetcode 全排列2-CSDN博客">LeetCode - 47 全排列 II_leetcode 全排列2-CSDN博客</a></p> 
<p></p> 
<p></p> 
<p>本题和leetcode47区别在于&#xff1a;</p> 
<p>石碑碎片内容可能是多个字母&#xff0c;比如用例3&#xff1a;</p> 
<p><img alt="" height="364" src="https://img-blog.csdnimg.cn/direct/e535f78260c54454958eb6b5db8ad9cd.png" width="706" /></p> 
<p>此时树层去重是无法检测出来的&#xff0c;因此我们还需要对求出来的全排列字符串进行一次去重</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81" style="background-color:transparent;">JS算法源码</h4> 
<pre><code class="language-javascript">const rl &#61; require(&#34;readline&#34;).createInterface({ input: process.stdin });
var iter &#61; rl[Symbol.asyncIterator]();
const readline &#61; async () &#61;&gt; (await iter.next()).value;

void (async function () {
  // 输入获取
  const n &#61; parseInt(await readline());
  const arr &#61; (await readline()).split(&#34; &#34;);

  const res &#61; new Set();
  const used &#61; new Array(n).fill(false);
  const path &#61; [];

  // 排序是为了让相同元素相邻&#xff0c;方便后面树层去重
  arr.sort();
  dfs(arr, used, path, res);

  // 输出石碑文字的组合&#xff08;按照升序排列&#xff09;
  [...res].sort().forEach((val) &#61;&gt; console.log(val));
})();

function dfs(arr, used, path, res) {
  if (path.length &#61;&#61; arr.length) {
    res.add(path.join(&#34;&#34;));
    return;
  }

  for (let i &#61; 0; i &lt; arr.length; i&#43;&#43;) {
    if (used[i]) continue;

    // 树层去重
    if (i &gt; 0 &amp;&amp; arr[i] &#61;&#61; arr[i - 1] &amp;&amp; !used[i - 1]) continue;

    path.push(arr[i]);
    used[i] &#61; true;
    dfs(arr, used, path, res);
    used[i] &#61; false;
    path.pop();
  }
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;

public class Main {
  static int n;
  static String[] arr;

  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    n &#61; Integer.parseInt(sc.nextLine());
    arr &#61; sc.nextLine().split(&#34; &#34;);

    getResult();
  }

  public static void getResult() {
    // 排序是为了让相同元素相邻&#xff0c;方便后面树层去重
    Arrays.sort(arr);

    boolean[] used &#61; new boolean[n];
    LinkedList&lt;String&gt; path &#61; new LinkedList&lt;&gt;();
    HashSet&lt;String&gt; res &#61; new HashSet&lt;&gt;();

    dfs(used, path, res);

    // 输出石碑文字的组合&#xff08;按照升序排列&#xff09;
    res.stream().sorted(String::compareTo).forEach(System.out::println);
  }

  public static void dfs(boolean[] used, LinkedList&lt;String&gt; path, HashSet&lt;String&gt; res) {
    if (path.size() &#61;&#61; n) {
      StringBuilder sb &#61; new StringBuilder();
      path.forEach(sb::append);
      res.add(sb.toString());
      return;
    }

    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      if (used[i]) continue;

      // 树层去重
      if (i &gt; 0 &amp;&amp; arr[i].equals(arr[i - 1]) &amp;&amp; !used[i - 1]) continue;

      path.addLast(arr[i]);
      used[i] &#61; true;
      dfs(used, path, res);
      used[i] &#61; false;
      path.removeLast();
    }
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
n &#61; int(input())
arr &#61; input().split()


# 全局变量
path &#61; []
used &#61; [False] * n
cache &#61; set()


# 全排列求解
def dfs():
    if len(path) &#61;&#61; n:
        cache.add(&#34;&#34;.join(path))
        return

    for i in range(n):
        if used[i]:
            continue

        # 树层去重
        if i &gt; 0 and arr[i] &#61;&#61; arr[i-1] and not used[i-1]:
            continue

        path.append(arr[i])
        used[i] &#61; True
        dfs()
        used[i] &#61; False
        path.pop()


# 算法入口
def getResult():
    # 排序是为了让相同元素相邻&#xff0c;方便后面树层去重
    arr.sort()
    dfs()

    # 输出石碑文字的组合&#xff08;按照升序排列&#xff09;
    for v in sorted(list(cache)):
        print(v)


# 算法调用
getResult()
</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>